<?php

namespace App\Console\Commands\SmsPool;

use App\Models\SmsPool;
use App\Services\SmsService;
use Illuminate\Console\Command;

class SmsPoolCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sms_pool_send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '短信池';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sms_service = null;
        try {
            $sms_service = new SmsService();
        } catch (\Throwable $th) {
            return;
        }
        $i = 0;
        while ($i <= 50) {
            $i++;
            $sms_pool = SmsPool::query()->where('status', SmsPool::STATUS_PENDING)->first();
            if (!$sms_pool) {
                continue;
            }
            # 标记发送中
            $sms_pool->update(['status' => SmsPool::STATUS_SENDING]);

            $receiverLocalUser = [];
            $user = [];
            if ($sms_pool->type == SmsPool::TYPE_BY_PHONE || $sms_pool->type ==  SmsPool::TYPE_BY_PHONEANDEMAIL) {
                if ($sms_pool->phone) {
                    $user['userMob'] = $sms_pool->phone;
                }
            }
            if ($sms_pool->type == SmsPool::TYPE_BY_EMAIL || $sms_pool->type ==  SmsPool::TYPE_BY_PHONEANDEMAIL) {
                if ($sms_pool->email) {
                    $user['userEmail'] = $sms_pool->email;
                }
            }
            if (count($user) > 0 && $sms_pool->content) {
                $receiverLocalUser = [$user];
                try {
                    $sms_service->sendPushed($receiverLocalUser, $sms_pool->title, $sms_pool->content);
                    $sms_pool->update(['status' => SmsPool::STATUS_SUCCESS, 'sms_send_at' => date("Y-m-d H:i:s")]);
                } catch (\Throwable $th) {
                    $sms_pool->update(['status' => SmsPool::STATUS_FAILED]);
                }
            }
        }
    }
}
